<template>
	<div class="system-user-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="userDialogFormRef" :model="state.ruleForm" size="default" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="账户名称" prop="username">
							<el-input v-model="state.ruleForm.username" placeholder="请输入账户名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="用户昵称">
							<el-input v-model="state.ruleForm.nickName" placeholder="请输入用户昵称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="关联角色">
							<el-select v-model="state.ruleForm.roleIds" multiple placeholder="请选择" clearable class="w100">
								<el-option
									v-for="role in roleList"
									:key="role.id"
									:label="role.name"
									:value="role.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="部门">
							<el-cascader :options="deptList"
								:props="{ checkStrictly: true, value: 'id', label: 'name' }" placeholder="请选择部门"
								clearable class="w100" v-model="state.ruleForm.deptId">
								<template #default="{ node, data }">
									<span>{{ data.name }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="岗位">
							<el-select v-model="state.ruleForm.postIds" multiple placeholder="请选择" clearable class="w100">
								<el-option
									v-for="post in postList"
									:key="post.id"
									:label="post.name"
									:value="post.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="手机号">
							<el-input v-model="state.ruleForm.phone" placeholder="请输入手机号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="邮箱">
							<el-input v-model="state.ruleForm.email" placeholder="请输入" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="性别">
							<el-select v-model="state.ruleForm.sex" placeholder="请选择" clearable class="w100">
								<el-option
									v-for="sex in sexData"
									:key="'sex-'+sex.value"
									:label="sex.label"
									:value="sex.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="用户状态">
							<el-switch v-model="state.ruleForm.status" inline-prompt active-text="启"
								inactive-text="禁" active-value="0" inactive-value="1"></el-switch>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="用户描述">
							<el-input v-model="state.ruleForm.remark" type="textarea" placeholder="请输入用户描述"
								maxlength="150"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="头像">
							<el-upload
								v-model:file-list="fileList"
								list-type="picture-card"
								:action="userApi().upload"
								:on-success="handleAvatarSuccess"
								:before-upload="beforeAvatarUpload"
								:on-preview="handlePictureCardPreview"
								:limit="1"
							>
							<el-icon><Plus /></el-icon>
							</el-upload>
							<el-dialog v-model="dialogVisible">
								<img w-full :src="dialogImageUrl" alt="Preview Image" />
							</el-dialog>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemUserDialog">
import { reactive, ref, onMounted, nextTick, getCurrentInstance } from 'vue';
import { userApi } from '/@/api/system/user';
import { postApi } from '/@/api/system/post';
import { roleApi } from '/@/api/system/role';
import { deptApi } from '/@/api/system/dept';
import constConfig from '/@/utils/constConfig';
import { Plus } from '@element-plus/icons-vue'
import { UploadProps, UploadUserFile, ElMessage } from 'element-plus'

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const { proxy } = <any>getCurrentInstance();

const props = defineProps({
    sexData:{
      type:Array,
      default:()=>[]
    }
})
// 定义变量内容
const roleList = ref([]);
const postList = ref([]);
const deptList = ref([]);
const userDialogFormRef = ref();
const state = reactive({
	ruleForm: {} as RowUserType,
	deptData: [] as DeptTreeType[], // 部门数据
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
	rules: {
		username: { required: true, message: "帐户名不能为空", trigger: "blur" },
	},
});

const fileList = ref<UploadUserFile[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response
) => {
	state.ruleForm.avatarPath = response.data;
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type.indexOf('image')==-1) {
    ElMessage.error('请上传正确图片格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片不能超过 10MB!')
    return false
  }
  return true
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
// 打开弹窗
const openDialog = (type: string, row: RowUserType) => {
	state.dialog.type = type;
	state.dialog.isShowDialog = true;
	state.ruleForm = row;
	if (type === constConfig.dialogType.add) {
		state.dialog.title = '新增用户';
		state.dialog.submitTxt = '新 增';
	} else {
		if (row.avatarPath) {
			fileList.value.push(proxy.getUpFileUrl(row.avatarPath))
		}
		getSelectData(row);
		state.dialog.title = '修改用户';
		state.dialog.submitTxt = '修 改';
	}
	nextTick(() => {
		userDialogFormRef.value.clearValidate();
	});
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {
	userDialogFormRef.value.validate((valid: boolean) => {
		if (valid) {
			if (state.dialog.type === constConfig.dialogType.add) {
				userApi().save(state.ruleForm).then(() =>{
					closeDialog();
					emit('refresh');
				})
			} else {
				userApi().update(state.ruleForm).then(()=>{
					closeDialog();
					emit('refresh');
				})
			}
		}
	})
};
// 初始化部门数据
const getSelectData = (row: RowUserType) => {
	userApi().getRoleListString(row.id).then((res: any) => {
		state.ruleForm.roleIds = res.data;
	});
	userApi().getPostListString(row.id).then((res: any) => {
		state.ruleForm.postIds = res.data;
	})

};
onMounted(() => {
	deptApi().tree().then((res: any) => {
		deptList.value = res.data
	})
	postApi().getAll().then((res: any) => {
		postList.value = res.data ?? [];
	});
	roleApi().getAll().then((res: any) => {
		roleList.value = res.data ?? [];
	})
});

// 暴露变量
defineExpose({
	openDialog,
});
</script>
